import dayjs from "dayjs";
export function msToYMDHMS(milliseconds, type = 1) {
  const date = new Date(milliseconds);
  const year = date.getFullYear();
  const month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的
  const day = ('0' + date.getDate()).slice(-2);
  const hours = ('0' + date.getHours()).slice(-2);
  const minutes = ('0' + date.getMinutes()).slice(-2);
  const seconds = ('0' + date.getSeconds()).slice(-2);
  const weeks = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六']
  const weekDay = weeks[date.getDay()]
  if(type == 1) return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  if(type == 2) return `${year}${month}${day}${hours}${minutes}${seconds}`
  if(type == 3) return `${year}年${month}月${day}日 ${weekDay}`
}



export  function msToTime(milliseconds) {
  var hours = Math.floor(milliseconds / 3600),
    minutes = Math.floor((milliseconds % 3600) / 60),
    seconds = Math.floor((milliseconds % 3600) % 60) 
  
  hours = hours < 10 ? '0' + hours : hours;
  minutes = minutes < 10 ? '0' + minutes : minutes;
  seconds = seconds < 10 ? '0' + seconds : seconds;
  
  return hours + ':' + minutes + ':' + seconds;
}
export function convertToFlat(data, parentId = null) {
  return data.reduce((acc, curr) => {
      acc.push({ ...curr, parentId });
      if (curr.children) {
          acc = acc.concat(convertToFlat(curr.children, curr.id));
      }
      return acc;
  }, []);
}

export function findDictNameByValue(data, dictValue) {
  return data.find(item => item.dictValue === dictValue)?.dictName;
}

export function timeAgo(createTime) {
  const createDate = new Date(createTime);
  const now = new Date();
  const diffInSeconds = Math.floor((now - createDate) / 1000); // 计算秒级时间差
  
  // 定义时间单位（按从大到小顺序）
  const units = [
    { label: '年', seconds: 60 * 60 * 24 * 365 },
    { label: '个月', seconds: 60 * 60 * 24 * 30 },
    { label: '天', seconds: 60 * 60 * 24 },
    { label: '小时', seconds: 60 * 60 },
    { label: '分钟', seconds: 60 },
    { label: '秒', seconds: 1 }
  ];

  // 遍历匹配最合适的时间单位
  for (const unit of units) {
    const diff = Math.floor(diffInSeconds / unit.seconds);
    if (diff > 0) {
      return `${diff}${unit.label}前`;
    }
  }
  return '刚刚'; // 小于1秒的情况
}
export function Copy(text) {
  if (!text) return null
  // 动态创建 textarea 标签
  const textarea = document.createElement('textarea')
  // 将该 textarea 设为 readonly 防止 iOS 下自动唤起键盘，同时将 textarea 移出可视区域
  textarea.readOnly = true
  textarea.style.position = 'absolute'
  textarea.style.left = '-9999px'
  // 将要 copy 的值赋给 textarea 标签的 value 属性
  textarea.value = text
  // 将 textarea 插入到 body 中
  document.body.appendChild(textarea)
  // 选中值并复制
  textarea.select()
  const result = document.execCommand('Copy')
  if (result) {
    ElMessage.success({
      message: '复制成功',
      showClose: true,
    }) // 可根据项目UI仔细设计
  } else {
    ElMessage.error({
      message: '复制失败',
      showClose: true,
    }) // 可根据项目UI仔细设计
  }
  document.body.removeChild(textarea)
}
// 文件下载函数
export function fileDownload(response) {
  // function fileDownLoad({ url, name, type }) {
    const downloadElement = document.createElement('a')
    downloadElement.style.display = "none";
    downloadElement.href = url
    downloadElement.download = `${name}${Date.now()}.${type}` // 下载后文件名
    document.body.appendChild(downloadElement)
    downloadElement.click() // 点击下载
    document.body.removeChild(downloadElement) // 下载完成移除元素
 }
  // 时间今天昨天几天前
 export function getDayName(createdTime) {
  const time = createdTime.replace(/-/g, "/");

  var td = new Date();
  td = new Date(td.getFullYear(), td.getMonth(), td.getDate());
  var od = new Date(time);
  od = new Date(od.getFullYear(), od.getMonth(), od.getDate());
  var xc = (od - td) / 1000 / 60 / 60 / 24;
  if (xc < -2) {
    return -xc + "天前";
  } else if (xc < -1) {
    return "前天";
  } else if (xc < 0) {
    return "昨天";
  } else if (xc == 0) {
    return "今天";
  }
};
// 一维数组转二维数组
export function getformat(list) {
  let arr = [];
  list?.forEach((item) => {
    let { createdTime, name, id, userId } = item;
    let time = dayjs(createdTime).format("YYYY-MM-DD");
    if (!arr[time]) {
      arr[time] = {
        createdTime: time,
        list: [],
      };
    }
    arr[time].list.push({
      id: id,
      name: name,
      userId: userId,
      isRename: false
    });
  });
  return Object.values(arr);
};